package com.sso.shiro;

import java.util.*;

import com.sso.entity.SysMenuRole;
import com.sso.entity.SysUserMenu;
import com.sso.entity.SysUserRole;
import com.sso.entity.view.SysMenuResourceView;
import com.sso.exception.SelectException;
import com.sso.manager.*;
import com.tools.util.StrUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.sso.entity.SysUser;

/**
 * 用户登陆和管理管理类
 */
public class RealmManager extends AuthorizingRealm {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private SysUserManager userManager;
	@Autowired
	private SysMenuResourceViewManager menuResourceViewManager;
	@Autowired
	private SessionDAO sessionDAO;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		if (!SecurityUtils.getSubject().isAuthenticated()) {
			doClearCache(principals);
			SecurityUtils.getSubject().logout();
			return null;
		}
		String username = (String) principals.getPrimaryPrincipal();
		SysUser user = userManager.selectByUsername(username);
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		List<SysMenuResourceView> menuResourceViewList = menuResourceViewManager.loadUserResource(user.getId());
		Set<String> perms = new HashSet<String>();
		for(SysMenuResourceView view : menuResourceViewList){
			perms.add(view.getMenuEname());
		}
		authorizationInfo.setStringPermissions(perms);
		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken)authcToken;
		String username = token.getUsername();
		SysUser user = userManager.selectByUsername(username);
		if (StrUtils.isEmpty(user.getId())) {
			throw new UnknownAccountException();// 没找到帐号
		}
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
				user.getUsername(), // 用户名
				user.getPassword(), // 密码
				getName() // realm name
		);
		return authenticationInfo;
	}

	/**
	 * 清除权限缓存
	 * @param username
     */
	public void clearUserChache(String username){
		logger.info("************开始清除用户权限缓存**************");
		Subject sub = SecurityUtils.getSubject();
		PrincipalCollection pri = sub.getPrincipals();
		PrincipalCollection principals = new SimplePrincipalCollection(
				username, getName());
		System.out.println(pri.hashCode());
		System.out.println(principals.hashCode());
		this.clearCachedAuthorizationInfo(principals);
		logger.info("********用户："+username+"的权限缓存已经清除***********");
	}

	/**
	 * 清除所有用户权限
	 */
	public void clearAllUserCache(){
		Collection<Session> sessions = sessionDAO.getActiveSessions();
		Iterator it = sessions.iterator();
		while(it.hasNext()) {
			Session session = (Session) it.next();
			String username = session.getAttribute("org.apache.shiro.subject.support.DefaultSubjectContext_PRINCIPALS_SESSION_KEY").toString();
			this.clearUserChache(username);
		}
	}


}
